﻿using System.ServiceModel.DomainServices.Server;
using Microsoft.Practices.Unity;
using System;
using AbstraX.ServerInterfaces;
using SolutionFramework.Entities;
using AbstraX.AssemblyInterfaces;
using AbstraX.Contracts;

namespace SolutionFramework.Web
{
    public class DomainServiceFactory : IDomainServiceFactory
    {
        private IUnityContainer container = null;

        public DomainServiceFactory(IUnityContainer container)
        {
            if (container == null)
                throw new ArgumentNullException("unityContainer");

            this.container = container;
        }

        public DomainService CreateDomainService(Type type, DomainServiceContext context)
        {
            var service = container.Resolve(type) as DomainService;
            service.Initialize(context);

            if (service is IAssemblyProviderService)
            {
                Global.DomainServiceHostApplication.AssemblyProviderService = (IAssemblyProviderService) service;
            }

            if (service is IAbstraXService)
            {
                var abstraXService = (IAbstraXService)service;

                abstraXService.DomainServiceHostApplication = Global.DomainServiceHostApplication;
            }

            if (service is IBindingsTreeService)
            {
                var bindingsTreeService = (IBindingsTreeService)service;

                bindingsTreeService.DomainServiceHostApplication = Global.DomainServiceHostApplication;
            }

            if (service is IEventsService)
            {
                var eventsService = (IEventsService)service;

                Global.DomainServiceHostApplication.EventsService = eventsService;
            }

            if (service is IAbstraXProviderService)
            {
                var abstraXProviderService = (IAbstraXProviderService) service;
                var rootID = abstraXProviderService.GetRootID();

                if (!Global.DomainServiceHostApplication.RegisteredServices.ContainsKey(rootID))
                {
                    Global.DomainServiceHostApplication.RegisteredServices.Add(rootID, abstraXProviderService);
                }
            }

            return service;
        }

        public void ReleaseDomainService(DomainService service)
        {
            service.Dispose();
        }
    }
}